import { Spin } from 'antd'
import c from 'classnames'
import { Suspense } from 'react'
import { useResize } from '@/desktop/logics/resize'
import { useStreams } from '@/lib/utils'
import useUIMemory from '@/logics/memory'
import services from '@/services'
import { useChatSidebars } from './logics'
import './index.module.less'

export { useChatSidebars }

export default function Sidebars() {
  const [contact] = useStreams(services.contacts.current.contact)
  const { showingSidebar, usableSidebars, setSidebar } = useChatSidebars()

  const [size, setSize] = useUIMemory<number>('sidebar-size', 350)
  const resizeEvents = useResize({
    side: 'x',
    reverse: true,
    min: 250,
    max: () => document.body.clientWidth * 0.5,
    current: size,
    onResize: setSize,
  })

  if (!contact || showingSidebar === null) return null

  return <>
    <div styleName="chat-sidebar" style={{ width: `${size}px` }}>
      <div css={resizerStyle} {...resizeEvents}></div>
      <header>
        {usableSidebars.map(sidebar => <div
          key={sidebar.key}
          styleName={c('tab', sidebar.key === showingSidebar.key && 'current')}
          onClick={() => setSidebar(sidebar.key)}
        >
          {sidebar.name}
        </div>)}
      </header>
      <main>
        <Suspense fallback={<TabLoading />}>
          <showingSidebar.Component key={showingSidebar.reset ? contact.id : 'sidebar'} />
        </Suspense>
      </main>
    </div>
  </>
}

function TabLoading() {
  return <div styleName="tab-loading">
    <Spin className="qun-spin" tip="载入中..." />
  </div>
}

const resizerStyle = css`
  bottom: 0;
  cursor: ew-resize;
  left: -1px;
  position: absolute;
  top: 0;
  width: 5px;
  z-index: 1;
`
